package com.frejoys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.dto.admin.OrderSnAndPageDto;
import com.frejoys.common.enums.EOrderType;
import com.frejoys.common.enums.EStatus;
import com.frejoys.common.util.AppConfigUtil;
import com.frejoys.common.util.CommonUtil;
import com.frejoys.common.vo.admin.OrderGoodsListVo;
import com.frejoys.common.vo.app.GoodsNameAndCoverVo;
import com.frejoys.common.vo.order.OrderGoodsVo;
import com.frejoys.dao.entity.Category;
import com.frejoys.dao.entity.Goods;
import com.frejoys.dao.entity.Order;
import com.frejoys.dao.entity.OrderGoods;
import com.frejoys.dao.mapper.CategoryMapper;
import com.frejoys.dao.mapper.GoodsMapper;
import com.frejoys.dao.mapper.OrderGoodsMapper;
import com.frejoys.dao.mapper.OrderMapper;
import com.frejoys.service.OrderGoodsService;
import com.frejoys.service.OrderService;
import jodd.util.CollectionUtil;
import lombok.RequiredArgsConstructor;
import org.bouncycastle.voms.VOMSAttribute;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wangzhicheng
 * @version 1.0
 * @date 2024/4/16 11:54
 */
@Service
@RequiredArgsConstructor
public class OrderGoodsServiceImpl extends ServiceImpl<OrderGoodsMapper, OrderGoods> implements OrderGoodsService {


    private final GoodsMapper goodsMapper;

    private final CategoryMapper categoryMapper;

    private final OrderMapper orderMapper;

    @Override
    public boolean addInfo(List<OrderGoods> list) {
        return saveBatch(list);
    }

    @Override
    public List<OrderGoods> getGoodsListByOrderSn(Long orderSn) {
        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(OrderGoods::getGoodsId, OrderGoods::getNum).eq(OrderGoods::getOrderSn, orderSn);
        return list(wrapper);
    }

    /**
     * 根据订单编号查询订单商品明细信息
     *
     * @param orderSn
     */
    @Override
    public List<OrderGoodsVo> getGoodsListDetailByOrderSn(Long orderSn) {
        List<OrderGoodsVo> goodsVos = new ArrayList<>();

        //查询出订单商品
        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(OrderGoods::getGoodsId, OrderGoods::getNum, OrderGoods::getPrice, OrderGoods::getPriceTotal).eq(OrderGoods::getOrderSn, orderSn).eq(OrderGoods::getStatus, EStatus.on.getValue());
        List<OrderGoods> orderGoods = list(wrapper);

        if (ObjectUtil.isNotEmpty(orderGoods)) {

            //筛选出包含的商品id
            List<Integer> goodsIds = orderGoods.stream().map(OrderGoods::getGoodsId).toList();

            //查询出对应商品参数
            LambdaQueryWrapper<Goods> goodsWrapper = Wrappers.lambdaQuery();
            goodsWrapper.select(Goods::getId, Goods::getCategoryId, Goods::getName, Goods::getCover).in(Goods::getId, goodsIds);
            List<Goods> goodsList = goodsMapper.selectList(goodsWrapper);
            Map<Integer, Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, goods -> goods));

            //查询出对应商品品目名称
            List<Integer> categoryIds = goodsList.stream().map(Goods::getCategoryId).toList();
            LambdaQueryWrapper<Category> categoryWrapper = Wrappers.lambdaQuery();
            categoryWrapper.select(Category::getId, Category::getName).in(Category::getId, categoryIds);
            List<Category> categories = categoryMapper.selectList(categoryWrapper);
            Map<Integer, String> categoryMap = categories.stream().collect(Collectors.toMap(Category::getId, Category::getName));

            for (OrderGoods goods : orderGoods) {
                OrderGoodsVo goodsVo = new OrderGoodsVo();
                BeanUtils.copyProperties(goods, goodsVo);
                goodsVo.setGoodsName(goodsMap.get(goods.getGoodsId()).getName());
                goodsVo.setCover(CommonUtil.getFirstCover(goodsMap.get(goods.getGoodsId()).getCover()));
                goodsVo.setCategoryId(goodsMap.get(goods.getGoodsId()).getCategoryId());
                goodsVo.setCategoryName(categoryMap.get(goodsVo.getCategoryId()));
                goodsVos.add(goodsVo);
            }
        }
        return goodsVos;
    }

    @Override
    public IPage<OrderGoodsListVo> orderGoodsListInfo(OrderSnAndPageDto dto) {
        Page page = new Page<>(dto.getPage(), dto.getSize());

        //查询订单编号是否是实物订单
//        if (dto.getOrderSn() != null){
//            LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
//            orderWrapper.select(Order::getType);
//
//            orderWrapper.eq(Order::getOrderSn,dto.getOrderSn());
//            Order order = orderMapper.selectOne(orderWrapper);
//
//            if (ObjectUtil.isEmpty(order)){
//                return new Page<>();
//            }
//            if (order.getType() != EOrderType.goodsOrder.getValue()){
//                return new Page<>();
//            }
//        }

        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        if (dto.getOrderSn() != null){
            wrapper.eq(OrderGoods::getOrderSn,dto.getOrderSn());
        }
        if (StrUtil.isNotEmpty(dto.getGoodsName())){
            List<Integer> goodsIds = goodsMapper.getGoodsNameById(dto.getGoodsName());
            if (goodsIds.isEmpty()){
                return new Page<>();
            }
            wrapper.in(OrderGoods::getGoodsId,goodsIds);
        }
        Page<OrderGoods> orderGoodsPage = baseMapper.selectPage(page, wrapper);
        IPage<OrderGoodsListVo> orderGoodsListVoIPage = orderGoodsPage.convert(orderGoods -> BeanUtil.copyProperties(orderGoods, OrderGoodsListVo.class));
        List<OrderGoodsListVo> list = orderGoodsListVoIPage.getRecords();

        if (!list.isEmpty()){
            List<Integer> goodsIds = list.stream().map(OrderGoodsListVo::getGoodsId).distinct().toList();

            //查询商品信息
            LambdaQueryWrapper<Goods> goodsWrapper = new LambdaQueryWrapper<>();
            goodsWrapper.select(Goods::getId,Goods::getName,Goods::getCover).in(Goods::getId,goodsIds);
            List<Goods> goodsList = goodsMapper.selectList(goodsWrapper);
            Map<Integer, Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, goods -> goods));

            list.forEach(vo ->{
                Goods goods = goodsMap.get(vo.getGoodsId());
                if (!ObjectUtil.isEmpty(goods)){
                    vo.setGoodsName(goods.getName());
                    vo.setCoverUrl(AppConfigUtil.getUrlPrefix(goods.getCover()));
                }
            });
        }
        return orderGoodsListVoIPage;
    }

    @Override
    public Map<Long, List<GoodsNameAndCoverVo>> goodsListByOrderSns(List<Long> orderSns) {

        LambdaQueryWrapper<OrderGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(OrderGoods::getOrderSn,OrderGoods::getGoodsId)
                .in(OrderGoods::getOrderSn,orderSns);
        List<OrderGoods> orderGoodsList = baseMapper.selectList(wrapper);

        Map<Long, List<GoodsNameAndCoverVo>> map = new HashMap<>();
        if (!orderGoodsList.isEmpty()){

            List<Integer> goodsIds = orderGoodsList.stream().map(OrderGoods::getGoodsId).toList();
            Map<Long, List<OrderGoods>> orderGoodsMap = orderGoodsList.stream().collect(Collectors.groupingBy(OrderGoods::getOrderSn));

            //查询商品信息
            LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Goods::getCover,Goods::getId,Goods::getName)
                    .in(Goods::getId,goodsIds);
            List<Goods> goodsList = goodsMapper.selectList(queryWrapper);
            Map<Integer, Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, goods -> goods));

            for (OrderGoods orderGoods:orderGoodsList) {
                if (orderGoodsMap.containsKey(orderGoods.getOrderSn())){
                    List<OrderGoods> orderGoodsLists = orderGoodsMap.get(orderGoods.getOrderSn());

                    List<GoodsNameAndCoverVo> vos = new ArrayList<>();
                    //插入商品信息
                    for (OrderGoods s:orderGoodsLists) {
                        if (goodsMap.containsKey(s.getGoodsId())){
                            GoodsNameAndCoverVo vo = new GoodsNameAndCoverVo();
                            vo.setName(goodsMap.get(s.getGoodsId()).getName());
                            vo.setId(goodsMap.get(s.getGoodsId()).getId());
                            vo.setCover(CommonUtil.getFirstCover(goodsMap.get(s.getGoodsId()).getCover()));
                            vos.add(vo);
                        }
                    }
                    map.put(orderGoods.getOrderSn(),vos);
                }
            }
        }
        return map;
    }

}
